package com.liqi.framework.web.service;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.liqi.common.constant.Constants;
import com.liqi.common.core.domain.AjaxResult;
import com.liqi.common.core.domain.entity.SysUser;
import com.liqi.common.core.domain.entity.UserInfo;
import com.liqi.common.core.domain.model.LoginUser;
import com.liqi.common.enums.UserStatus;
import com.liqi.common.exception.ServiceException;
import com.liqi.common.utils.SecurityUtils;
import com.liqi.common.utils.StringUtils;
import com.liqi.sms.utils.SmartHttp;
import com.liqi.sms.utils.TokenUtil;
import com.liqi.system.service.ISysUserService;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
public class TokenSsoDetailsServiceImpl implements UserDetailsService {
	private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

	@Autowired
	private ISysUserService userService;

	@Autowired
	private SysPermissionService permissionService;

	@Value("${MiddlePlatform.Url}")
	private String middlePlatformUrl;

	@Value("${MiddlePlatform.TokenUsername}")
	private String tokenUsername;

	@Value("${MiddlePlatform.TokenPassWord}")
	private String tokenPassWord;

	@Override
	public UserDetails loadUserByUsername(String token) throws UsernameNotFoundException {
		//第一步：通过中台接口，去政务与浪潮BSP系统，根据token拿用户信息
		UserInfo userinfo = null;
		long time = System.currentTimeMillis();
		
		Map<String, String> heardMap = new HashMap<>();
		heardMap.put("Authorization",TokenUtil.getToken(middlePlatformUrl + "auth/token", tokenUsername, tokenPassWord));
		Map<String, Object> resultmap = new HashMap();
		Map<String, String> params = new HashMap<>();
		params.put("clientId", "LIQI-YWGKXT");
		params.put("clientSecret", "2CVCR35EY34JMY7ESWTT");
		params.put("token", token);
		
		
		String msg = "";
		try {
			String body = SmartHttp.sendGet(middlePlatformUrl+ "util/peopleClub/getUserInfo", params, heardMap);
			
			log.info("统一登录，中台返回：" + body);
			
			JSONObject repJson = JSONObject.parseObject(body);
			Integer code = (Integer) repJson.get("code");
			if (200 != code) {
				msg = repJson.get("msg").toString();
				throw new ServiceException("用户登录的token：" + token + " ，在统一工作台验证不通过。");
			}
			String rspData = repJson.get("data").toString();
			if (rspData != null) {
				userinfo = JSON.parseObject(rspData, UserInfo.class);
			}
		} catch (Exception e) {
			log.error("请求统一工作台报错："+msg, e);
			throw new ServiceException("用户登录的token：" + token + " ，在统一工作台验证不通过。");
		}
		
		long time2 = System.currentTimeMillis();
		
		log.info("loginByToken单点登录，调中台时间差：" + (time2 - time) + " ms");	
		
		//第二步：根据用户名去查询当前用户是否已经注册过
		SysUser user = userService.selectUserByUserName(userinfo.getACCOUNT());
		
		//第三部：如果没有注册，那么走注册逻辑
		if(user == null) {
			user = new SysUser();
			user.setUserName(userinfo.getACCOUNT());
			user.setNickName(userinfo.getNAME());
			user.setPhonenumber(userinfo.getMOBILE());
			user.setEmail(userinfo.getEMAIL());
			user.setSex(userinfo.getGENDER());
			user.setStatus("0");
			user.setDelFlag("0");
			user.setCreateBy("admin");
	        user.setPassword(SecurityUtils.encryptPassword("2023@#cba!"));
	        //默认为统一工作台部门
	        user.setDeptId(112l);
	      //第四步：要拿到UserId
	        userService.insertUser(user);
		}
		
		//user = userService.selectUserByUserName("admin");
		if (StringUtils.isNull(user)) {
			log.info("登录用户：{} 不存在.", token);
			throw new ServiceException("登录用户：" + token + " 不存在");
		} else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
			log.info("登录用户：{} 已被删除.", token);
			throw new ServiceException("对不起，您的账号：" + token + " 已被删除");
		} else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
			log.info("登录用户：{} 已被停用.", token);
			throw new ServiceException("对不起，您的账号：" + token + " 已停用");
		}

		return createLoginUser(user);
	}

	public UserDetails createLoginUser(SysUser user) {
		return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
	}
}
